package com.example.airobotinterviewrecord.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.airobotinterviewrecord.entity.InterviewSchedule;
import com.example.airobotinterviewrecord.mapper.InterviewScheduleMapper;
import com.example.airobotinterviewrecord.service.IInterviewScheduleService;
import com.example.candiates.service.InterviewCandidatesService;
import com.example.question.service.QuestionSetService;
import com.example.question.entity.QuestionSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.Collections;

/**
 * <p>
 * 面试安排表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-07
 */
@Service
public class InterviewScheduleServiceImpl extends ServiceImpl<InterviewScheduleMapper, InterviewSchedule> implements IInterviewScheduleService {
    private static final Logger logger = LoggerFactory.getLogger(InterviewScheduleServiceImpl.class);

    @Autowired
    private InterviewCandidatesService candidatesService;
    
    @Autowired
    private QuestionSetService questionSetService;

    // 查询所有面试安排
    @Override
    public IPage<InterviewSchedule> listSchedulesByPage(int pageNum, int pageSize) {
        Page<InterviewSchedule> page = new Page<>(pageNum, pageSize);
        return this.page(page);
    }

    // 新增面试安排
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addSchedule(InterviewSchedule schedule) {
        try {
            logger.info("开始添加面试安排: {}", schedule);
            
            // 验证候选人是否存在
            if (schedule.getCandidateId() != null) {
                boolean candidateExists = candidatesService.getById(schedule.getCandidateId()) != null;
                if (!candidateExists) {
                    logger.error("候选人不存在, ID: {}", schedule.getCandidateId());
                    throw new IllegalArgumentException("候选人不存在");
                }
            }
            
            // 确保ID为null，让数据库自动生成
            schedule.setId(null);
            
            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            schedule.setCreatedAt(now);
            schedule.setUpdatedAt(now);
            
            if(schedule.getQuestionSetIds() != null && schedule.getQuestionSetIds().isEmpty()) {
                schedule.setQuestionSetIds(null);
            }
            
            boolean saved = save(schedule);
            if (saved) {
                logger.info("面试安排添加成功, ID: {}", schedule.getId());
            } else {
                logger.error("面试安排添加失败");
            }
            return saved;
        } catch (Exception e) {
            logger.error("添加面试安排时发生错误: ", e);
            throw e;
        }
    }

    // 根据ID删除面试安排
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteScheduleById(Integer id) {
        try {
            logger.info("开始删除面试安排, ID: {}", id);
            
            if (id == null) {
                logger.error("删除ID为空");
                throw new IllegalArgumentException("ID不能为空");
            }
            
            InterviewSchedule existing = getById(id);
            if (existing == null) {
                logger.error("记录不存在, ID: {}", id);
                throw new IllegalArgumentException("记录不存在");
            }
            
            boolean removed = removeById(id);
            if (!removed) {
                logger.error("删除记录失败, ID: {}", id);
                throw new RuntimeException("删除失败");
            }
            
            logger.info("面试安排删除成功, ID: {}", id);
            return "删除成功";
        } catch (Exception e) {
            logger.error("删除面试安排时发生错误: ", e);
            throw e;
        }
    }

    // 更新面试安排
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateSchedule(InterviewSchedule schedule) {
        try {
            logger.info("开始更新面试安排: {}", schedule);
            
            if (schedule == null || schedule.getId() == null) {
                logger.error("更新记录ID为空");
                throw new IllegalArgumentException("Id不能为空");
            }
            
            InterviewSchedule existing = getById(schedule.getId());
            if(existing == null) {
                logger.error("记录不存在, ID: {}", schedule.getId());
                throw new IllegalArgumentException("记录不存在");
            }

            // 验证候选人是否存在
            if (schedule.getCandidateId() != null) {
                boolean candidateExists = candidatesService.getById(schedule.getCandidateId()) != null;
                if (!candidateExists) {
                    logger.error("候选人不存在, ID: {}", schedule.getCandidateId());
                    throw new IllegalArgumentException("候选人不存在");
                }
            }

            if(schedule.getQuestionSetIds() == null) {
                schedule.setQuestionSetIds(existing.getQuestionSetIds());
            }

            boolean updated = updateById(schedule);
            if (!updated) {
                logger.error("更新记录失败, ID: {}", schedule.getId());
                throw new RuntimeException("更新失败");
            }
            
            logger.info("面试安排更新成功, ID: {}", schedule.getId());
            return "更新成功";
        } catch (Exception e) {
            logger.error("更新面试安排时发生错误: ", e);
            throw e;
        }
    }

    // 获取题目集列表
    @Override
    public List<QuestionSet> listQuestionSets() {
        try {
            if (questionSetService == null) {
                logger.error("QuestionSetService未正确注入");
                throw new RuntimeException("QuestionSetService未正确注入");
            }
            
            LambdaQueryWrapper<QuestionSet> wrapper = new LambdaQueryWrapper<>();
            // 移除状态限制，获取所有题目集
            wrapper.orderByAsc(QuestionSet::getOrderNum);  // 按排序号升序
            
            return questionSetService.list(wrapper);
        } catch (Exception e) {
            logger.error("获取题目集列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取题目集列表失败: " + e.getMessage(), e);
        }
    }
}
